﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.ServiceBus;
using Microsoft.ServiceBus.Messaging;

namespace OnlineStoreSystem
{
    public class ServiceBus<T>
    {
        private readonly string _topic;
        private readonly string _subscription;
        private readonly IList<Action<T>> _handlers;

        private SubscriptionClient _client;
        private Boolean _stop;
        
        public ServiceBus(String topic, String subscription)
        {
            _topic = topic;
            _subscription = subscription;
            _handlers = new List<Action<T>>();
        }

        public void Start()
        {
            var thread = new Thread(Runner);
            thread.Start();
        }

        public void Stop()
        {
            _stop = true;
        }

        public void AddHandler(Action<T> handler)
        {
            _handlers.Add(handler);
        }

        private void Runner()
        {
            ServiceBusEnvironment.SystemConnectivity.Mode = ConnectivityMode.Http;

            _client = SubscriptionClient.Create(_topic, _subscription);

            while (!_stop)
            {
                var message = _client.Receive(TimeSpan.FromSeconds(5));
                if (message != null)
                {
                    var body = message.GetBody<T>();

                    var handlers = _handlers.ToArray();
                    Array.ForEach(handlers, a => a(body));

                    message.Complete();
                }
                Thread.Sleep(200);
            }
        }
    }
}